<template>
  <!-- 质量整改通知单的操作页，包括：填报 0 ，调整 1 ，查看 2 -->
  <base-breadcrumb :title="$route.meta.title">
    <a-spin :spinning="loading">
      <a-card :bordered="false" class="base-info-style">
          <!-- 节点信息 -->
          <NodeInfo ref="NodeInfo" :onlyRead="true" v-if="showNodeInfo" />
          <!-- 基本信息 -->
          <BaseInfo ref="BaseInfo" :form="form" :onlyRead="onlyRead" />
          <!-- 重点监管质量风险监控计划信息 -->
          <RiskMonitoringPlanInfo ref="RiskMonitoringPlanInfo" :form="form" v-if="!onlyRead" />
          <RiskMonitoringPlanView ref="RiskMonitoringPlanView" :form="form" :api="api" v-else />
      </a-card>
      <!-- 页脚操作栏 -->
      <Footer
        :editModel="editModel"
        :loading="footerLoading"
        @submitDraft="submitDraft" 
        @submitFormal="submitFormal"
        v-if="!isFromAudit"
      />
    </a-spin>
    <div v-if="!isConsultation && isFromAudit" class="page-btn-right-top">
      <a-button
        v-check-visible-in-detail
        style="margin: 0 10px"
        @click="$close"
      >
        关闭
      </a-button>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { riskMonitorPlan } from '@/api/quality/risk/monitoringPlan'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置 
import NodeInfo from '@/views/quality/riskIdentification/components/NodeInfo' // 节点信息
import BaseInfo from '@/views/quality/riskIdentification/components/BaseInfo'
import RiskMonitoringPlanInfo from '@/views/quality/riskIdentification/components/RiskMonitoringPlanInfo'
import RiskMonitoringPlanView from '@/views/quality/riskIdentification/components/RiskMonitoringPlanView'
import Footer from '@/views/quality/riskIdentification/components/Footer'

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    NodeInfo,
    BaseInfo,
    RiskMonitoringPlanInfo,
    RiskMonitoringPlanView,
    Footer
  },
  props: {
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      id: this.$route.query.id || '',
      historyId: this.$route.query.historyId || '',
      loading: false, // 请求加载框
      editModel: this.$route.query.editModel || '0', // 操作类型：0 填报，1 编辑，2 查看, 3 调整
      form: {
        projectId:"",
        updateUserName: this.$userInfo().name,
        fillTime: this.$dateFormat(Date.now(), 'D'),
      },
      showNodeInfo: false,
      footerLoading: { 'submitDraft': false, 'submitFormal': false, 'submitValidate': false },
      api: riskMonitorPlan, // 请求api
      titles: ['填报', '编辑', '查看', '调整'], // 根据操作类型自适应的标题
      projectId: this.$route.query.projectId || '',
      branchComName: this.$route.query.branchComName || '',
      projectName: this.$route.query.projectName || '',
      isFromAudit: false, // 是否来自审批
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  async created() {
    this.$route.meta.title = [
      '重点监管质量风险监控计划填报',
      '重点监管质量风险监控计划编辑',
      '重点监管质量风险监控计划查看',
      '重点监管质量风险监控计划调整',
    ][this.editModel]
    this.isFromAudit = !!this.$route.query.businessId
    // 初始化
    this.init()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_risk_monitor_plan')
    const {
      taskId
    } = this.$route.query
    if (!!taskId) {
      this.showNodeInfo = true
    }
  },
  computed: {
    // 只读模式
    onlyRead() {
      return this.editModel == 2 || this.isFromAudit
    }
  },
  methods: {
    /**
     * @description: 初始化
     */
    init() {
      // 当操作为新增和生成整改单,则自动获取下发人和下发时间，否则请求业务详情
      if (this.id) {
        this.loading = true
        this.api
          .getDetail(this.id, this.historyId || '-1', this.onlyRead ? '1' : '0')
          .then((res) => {
            if (res.data) {
              // 映射表单
              this.form = res.data
              if (res.data.branchComName && res.data.projectName) {
                this.form.viewName = res.data.branchComName + '/' + res.data.projectName
              }
            }
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        this.form.fillerName = this.$userInfo()?.name
        this.form.fillerId = this.$userInfo().id
        this.form.modifiedTime = this.$dateFormat(new Date(), 'D')
        this.form.viewName = this.branchComName + '/' + this.projectName
        this.form.projectId = this.projectId
      }
    },
    submitDraft() {
      try {
        const dataSource = this.$refs.RiskMonitoringPlanInfo.dataSource || []
        this.submit('submitDraft', dataSource)
      } catch (e) {
        console.log(e)
      }
    },
    submitFormal() {
      try {
        const BaseInfo = this.$refs.BaseInfo
        BaseInfo.$refs?.ruleForm.validate(valid => {
        if (valid) {
          const columns1 = this.$refs.RiskMonitoringPlanInfo.columns || []
          const columns = columns1.filter(v => v.dataIndex !== 'action').map(item => item.dataIndex)
          const dataSource = this.$refs.RiskMonitoringPlanInfo.dataSource || []
          if (dataSource.length === 0) {
            this.$warning({
              title: '提示',
              content: '请填写质量风险监控计划信息',
              okText: '确定'
            })
            return false
          }
          const emtyArr = dataSource.filter((obj) => {
            let tag = false
            for (let key in obj) { 
              if (columns.indexOf(key) !== -1 && !obj[key]) {
                tag = true
                break;
              }
            }
            return tag;
          })
          if (emtyArr.length) {
            this.$warning({
              title: '提示',
              content: '请将质量请将风险监控计划信息填写完整再提交！',
              okText: '确定'
            })
            return false
          }
          const takeEffectDate = dataSource.filter(item => this.moment(item['takeEffectDate']).diff(this.moment(new Date()), 'days') < 0 && item.operation != false)
          if (takeEffectDate.length) {
            this.$warning({
              title: '提示',
              content: '生效日期不能小于今天',
              okText: '确定'
            })
            return false
          }
          if (this.processConfig == 4) {
            this.submit('submitFormal', dataSource)
          } else {
            this.$confirm({
              titile: '提示',
              content: '确认提交，提交后不可撤回？',
              onOk: () => {
                return this.submit('submitFormal', dataSource)
              }
            })
          }
          
        }
      })
      } catch (e) {
        console.log(e)
      }
    },
    /**
     * @description: 提交表单
     * @param {*} status
     * @return {*}
     */
     submit(status, dataSource) {
      let name = '' // 根据操作切换url地址
      if (this.id) {
        if (this.editModel == '3') {
          name = 'adjustment'
        } else {
          name = 'updatePost'
        }
      } else {
        name = 'handleCreate'
      }
      this.setProcessConfig = null;
      this.submitApprovalConfirm(status =='submitFormal' ? this.processConfig : 6, (flag)=>{
        if(!flag) {
          this.footerLoading[status] = true
          return
        }
        // 提交表单
        this.footerLoading[status] = true
        const statusCode = {submitDraft: 0, submitFormal: 1}[status]
        let form = this.$clone(this.form)
        form.status = statusCode
        form.details = dataSource
        this.api[name](form)
            .then((res) => {
              if (res.code === 200 || res.data.code === 200) {
                //提交时，返回id
                this.$message.success(['保存草稿', '提交'][statusCode] + '成功！')
                if (status =='submitFormal') {
                  this.businessId = res.data.id;
                  this.setProcessConfig = this.processConfig;
                  return
                }
                this.$multiTab.close()
            }
          })
          .finally(() => {
            this.footerLoading[status] = false
          })
      })
    },
  }
}
</script>